import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '../components/Login.vue'
import Welcome from '../components/Welcome.vue'
import User from '../components/User/User.vue'
import PowerList from '../components/Power/PowerList.vue'
import RolesList from '../components/Power/RolesList.vue'
import GoodsCategory from '../components/Goods/GoodsCategory.vue'
import CtaeParams from '../components/Goods/CtaeParams.vue'
import GoodsList from '../components/Goods/GoodsList.vue'
import AddGoods from '../components/Goods/AddGoods.vue'
import Order from '../components/Order/Order.vue'
import Report from '../components/Report/Report.vue'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

// 避免多次点击导航栏报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: User },
      { path: '/rights', component: PowerList },
      { path: '/roles', component: RolesList },
      { path: '/categories', component: GoodsCategory },
      { path: '/params', component: CtaeParams },
      { path: '/goods', component: GoodsList },
      { path: '/goods/add', component: AddGoods },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ],
    redirect: '/welcome'
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') next()
  const token = window.sessionStorage.getItem('token')
  if (!token) next('/login')
  next()
})

export default router
